<style lang=sass>
@import "../../assets/sass/calendar/calendar.scss";
</style>
<template>
<div class="vue-calendar" v-show="visible">
    <month v-for="item in monthItems" 
    :month="item"  
    :min-date="minDate"
    :max-date="maxDate"
    :selected-suffix="selectedSuffix"
    :selected-value="selectedValue"
    @changed="onChanged"
    ></month>
</div>
</template>

<script>
import monthItem from "./month"

export default{
    components:{
        "month":monthItem
    },
    props:{
        minDate:String,
        maxDate:String,
        months:String,
        visible:Boolean,
        selectedSuffix:String,
        selectedValue:String
    },
    data(){
        return {
            scrollY:0,
            monthItems:[]
        }  
    },
    created(){
        this.createMonthItems();
    },
    watch:{
        visible(){
            document.body.scrollTop=this.scrollY;
        }
    },
    methods:{
        onChanged(item){
            this.scrollY=document.body.scrollTop;
            this.$emit("changed",item);
        },
        createMonthItems(){
            let self=this;
            let _minDate=self.minDate?new Date(self.minDate):new Date();
            let _maxDate=self.maxDate?new Date(self.maxDate):setLastDate(self.minDate,this.months);
            let _monthItems=[];
            let i=0,_start,_next;
            while(i<self.months){
                _start=self.setLastDate(_minDate,i);
                _next=self.compareDate(_start,_maxDate);
                _monthItems.push({
                    monthText:self.getDateYear(_start)+"年"+self.getDateMonth(_start)+"月",
                    date:self.resetDate(_start)
                });
                i++;
            }
            self.monthItems=_monthItems;
        },
        setLastDate(date,months){
            let _date=new Date(date);
            let _year=_date.getFullYear();
            let _month=_date.getMonth()+months;
            let _day=_date.getDate();
            return new Date(_year,_month,_day);
        },
        getDateYear(d){
            return d.getFullYear();
        },
        getDateMonth(d){
            let _m;
            _m=d.getMonth()+1;
            return _m>12?12:_m;
        },
        resetDate(d){
            let _date;
            _date=d.setDate(1);
            return _date;
        },
        compareDate(a,b){
            let start=new Date(a),end=new Date(b);
            start.setHours(0);
            start.setMinutes(0);
            start.setSeconds(0);
            end.setHours(0);
            end.setMinutes(0);
            end.setSeconds(0);
            return start.getTime()-end.getTime();
        }
    }
}
</script>